/**
 * @file    Expression classname is undefined on line 2, column 15 in Templates/Classes/Class.java.
 * @author  Haseeb Yousaf
 * @see     LICENSE (MIT style license file)
 * @version 1.0
 * @date    Nov 17, 2011 4:35:30 PM
 */
package carrello.impl.controller.administrator;

import java.util.List;
import carrello.model.association.AssociationFactory;
import carrello.model.entitydao.CategoryDAO;
import carrello.model.association.AttributeValue;
import carrello.impl.controller.AbstractCTRL;
import carrello.model.association.CategoryAssociation;
import carrello.model.entities.*;
import static carrello.util.EntityManagerUtil.getEntityManager;

public class DeleteCategoryCTRL extends AbstractCTRL {

    public void delete(int cid) {
        deleteAssociation(cid);
        Category cat = new CategoryDAO().getById(cid);
        getEntityManager().beginUnitOfWork();
        deleteTree(cat);
        getEntityManager().endUnitOfWork();

    } // deleteCategory

    private void deleteTree(Category cat) {
        if ( cat.getchildren() != null || !cat.getchildren().isEmpty()) {
//            getEntityManager().beginUnitOfWork();
            if (!cat.getProduct().isEmpty()) {
                for (Product p : cat.getProduct()) {
                    new AttributeValue().delete(p);
                } // for
                AssociationFactory.createProductBelongsToCategory(cat, cat.getProduct()).deleteAll();
            }
            AssociationFactory.createCategoryHasAttributes(cat, cat.getAttribute()).deleteAll();
            getEntityManager().remove(cat);
            for (Category c_child : cat.getchildren()) {
                deleteTree(c_child);
            }
            // if there is no Children exist, remove the Category
        } else {
            if (!cat.getProduct().isEmpty()) {
                for (Product p : cat.getProduct()) {
                    new AttributeValue().delete(p);
                } // for
                AssociationFactory.createProductBelongsToCategory(cat, cat.getProduct()).deleteAll();
            }
            AssociationFactory.createCategoryHasAttributes(cat, cat.getAttribute()).deleteAll();
            getEntityManager().remove(cat);
        }
    }

    private void deleteAssociation(int cid)
    {
         List<CategoryAssociation> acList = CategoryAssociation.getAssociatedCategory(cid);
            for (CategoryAssociation ca : acList) {
                 getEntityManager().beginUnitOfWork();
                 getEntityManager().remove(ca);
                 getEntityManager().endUnitOfWork();
            } // for
    }
//    public static void main(String[] args) {
//        new DeleteCategoryCTRL().delete(3);
//    }
} // DeleteCategoryCTRL